from graphics import Image
from appuifw2 import query as query2
from appuifw import Text,app,Form,FFormDoubleSpaced,FFormEditModeOnly,note,Canvas,EScreen
from e32 import Ao_lock,drive_list,start_exe,ao_sleep
from os import path as ospath
from codecs import open as openfile
from struct import unpack,pack
from appswitch import kill_app
from sys import path as syspath

__doc__='Power mod by Atrant of Lite filemanager by Shrim'
__name__='PowLite FM'
class manager:
  def __s2d(s,x):
    res = ""
    x = x.lower()
    for i in range(len(x)):
      ind = s.alphabet.find(x[i])
      if ind == -1: res += "1"
      else: res += s.numaplhabet[ind]
    return res
  def ru(s,x):
    return x.decode('utf-8')
  def ur(s,x):
    return x.encode('utf-8')
  def __init__(s):
    import appuifw,os,e32
    s.appuifw, s.os, s.e32 = appuifw,os,e32
    s.lock = s.e32.Ao_lock()
    s.curdir = None
    s.alphabet =  s.ru("abcdefghijklmnopqrstuvwxyz1234567890 ")
    s.numaplhabet =   u"2223334445556667777888999922223333344445555666677778888999912345678900"
  def AskUser(s, path = None, find = 'file', ext = [], title = 'Select file ...', wait = 'Wait...', mselect = 'Select', mopen = 'Open', mback = 'Back'):
    #s.cartella='c:\\python\\'
    #splashfile=u'%sNetAlarm GUI.mif' % (s.cartella)
    #s.iconpath = u"C:\\system\\data\\powlite_fm.mbm"
    s.iconpath = splashfile
    if not s.os.path.exists(s.iconpath):
      s.appuifw.app.note(s.ru("Graphics file not found!"),'error')
      return None

    icon = s.appuifw.Icon(s.iconpath,16394,16395)
    s.workitem = (s.ru(wait),icon)
    icon = s.appuifw.Icon(s.iconpath,16392,16393)
    s.backitem = (u'<<<',icon)

    if path == None and s.curdir != None and s.curdir != u'root':
      path = s.os.path.split(s.curdir)[0]
      if path[-1] != '\\': path += '\\'
    s.oldscreen = s.appuifw.app.screen
    s.oldbody = s.appuifw.app.body
    s.oldexitkeyhandler = s.appuifw.app.exit_key_handler
    s.oldmenu = s.appuifw.app.menu
    s.oldtitle = s.appuifw.app.title
    try:
      s.oldfocus = s.appuifw.app.body.focus
      s.appuifw.app.body.focus = False
    except: pass
    if find == 'dir': s.appuifw.app.title = s.ru(title)
    else: s.appuifw.app.title = s.ru(title)

    s.find, s.ext = find, ext

    s.appuifw.app.screen = 'normal'
    s.appuifw.app.body = s.body = s.appuifw.Listbox(s.list_root())
    s.appuifw.app.exit_key_handler = s.exit
    s.menuChoose = (s.ru(mselect),s.choose_item)
    s.menuOpen = (s.ru(mopen),s.browse_forward)
    s.menuBack = (s.ru(mback),s.browse_back)

    s.curlist = s.list_root()

    if not path: s.root()
    else:
      try:
        path = s.ru(path)
      except:
        pass
      s.curdir = s.os.path.normpath(path)
      if s.curdir[-1] != '\\':
        s.curdir = s.curdir + '\\'
      if s.os.path.exists(s.ur(path)) and s.os.path.isdir(s.ur(path)):
        s.listdir()
      else: s.root()

    s.body.bind(63495,s.browse_back)
    s.body.bind(63557,s.browse_forward)
    s.body.bind(63496,s.choose_item)
    s.body.bind(63497,lambda: s.construct_menu(-1))
    s.body.bind(63498,lambda: s.construct_menu(1))
    s.body.bind(48,lambda: s.listslice(u"0"))
    s.body.bind(49,lambda: s.listslice(u"1"))
    s.body.bind(50,lambda: s.listslice(u"2"))
    s.body.bind(51,lambda: s.listslice(u"3"))
    s.body.bind(52,lambda: s.listslice(u"4"))
    s.body.bind(53,lambda: s.listslice(u"5"))
    s.body.bind(54,lambda: s.listslice(u"6"))
    s.body.bind(55,lambda: s.listslice(u"7"))
    s.body.bind(56,lambda: s.listslice(u"8"))
    s.body.bind(57,lambda: s.listslice(u"9"))
    s.body.bind(8,lambda: s.listslice(u"C"))
    s.construct_menu(0)

    s.lock.wait()

    s.body.bind(63495,None)
    s.body.bind(63557,None)
    s.body.bind(63496,None)
    s.body.bind(63497,None)
    s.body.bind(63498,None)
    s.body.bind(48,None)
    s.body.bind(49,None)
    s.body.bind(50,None)
    s.body.bind(51,None)
    s.body.bind(52,None)
    s.body.bind(53,None)
    s.body.bind(54,None)
    s.body.bind(55,None)
    s.body.bind(56,None)
    s.body.bind(57,None)
    s.appuifw.app.body = s.oldbody
    s.appuifw.app.screen = s.oldscreen
    s.appuifw.app.exit_key_handler = s.oldexitkeyhandler
    s.appuifw.app.menu = s.oldmenu
    s.appuifw.app.title = s.oldtitle
    try: s.appuifw.app.body.focus = s.oldfocus
    except: pass
    tmp = None
    if s.choice_made:
      tmp = s.curdir
      if s.find == 'dir' and tmp[:-1]!='\\':
        tmp += '\\'

    if s.curdir != u'root':
      if s.find == 'file':
        s.curdir = s.os.path.split(s.curdir)[0]
      if s.curdir[-1] != '\\': s.curdir += '\\'
    #try:s.appuifw.note(tmp,'info')
    #except: pass
    return tmp

  def root(s, prevdir = None):
    t = s.list_root()
    posindex = 0
    for i in range(len(t)):
      #s.appuifw.note(t[i][0])
      if t[i][0] == prevdir:
        posindex = i
        break
    s.body.set_list(t,posindex)
    s.curdir = u'root'
    s.curlist = s.list_root()
    s.construct_menu(0)

  def construct_menu(s, add):
    def _set(x):
      s.appuifw.app.menu = x

    i = s.body.current() + add
    if i == -1: i = len(s.curlist) - 1
    elif i == len(s.curlist): i = 0
    if s.curdir == u'root':
      if s.find == 'dir':
        _set([s.menuChoose,s.menuOpen])
      else: _set([s.menuOpen])
      return
    elif i == 0:
      _set([s.menuChoose])
      return
    else:
      path = s.curdir + s.curlist[i][0]

    if s.os.path.isdir(s.ur(path)):
      if s.find == 'dir':
        _set([s.menuChoose,s.menuOpen,s.menuBack])
      else:
        _set([s.menuOpen,s.menuBack])
    else:
      _set([s.menuChoose,s.menuBack])

  def list_root(s):
    icon = s.appuifw.Icon(s.iconpath,16386,16387)
    resultlist = []
    for drive in s.e32.drive_list():
      resultlist.append((drive,icon))
    return resultlist

  def listslice(s,keycode):
    if keycode == u"C":
      if s.curnumstring == u"":
        return
      s.curnumstring = s.curnumstring[:-1]
      if s.curnumstring == u"":
        if s.appuifw.app.title[-1] == u"*":
          s.appuifw.app.title = s.appuifw.app.title[:-1]
        s.curlist = s.fulllist
        s.body.set_list(s.fulllist)
        return
    else: s.curnumstring += keycode
    if s.appuifw.app.title[-1] != u"*":
      s.appuifw.app.title += u"*"
    resultlist = [s.curlist[0]]
    #s.appuifw.note(s.curnumstring)
    for i in range(0,len(s.curnumlist)):
      if s.curnumlist[i].startswith(s.curnumstring):
        resultlist.append(s.fulllist[i+1])
    s.curlist = resultlist
    index = 0
    if len(resultlist) > 1: index = 1
    s.body.set_list(resultlist,index)

  def listdir(s, prevdir = None):
    #if prevdir:
      #s.appuifw.note(prevdir)
    if s.appuifw.app.title[-1] == u"*":
      s.appuifw.app.title = s.appuifw.app.title[:-1]
    resultlist = [s.backitem]
    s.curnumlist = []
    s.curnumstring = u""
    s.body.set_list( [s.workitem])
    s.e32.ao_yield()
    templist, files, folders = s.  os.listdir(s.ur(s.curdir)), [], []
    posindex = 0

    if templist:
      for item in templist:
        if s.os.path.isfile(s.ur(s.curdir) + item):
          if s.find == 'file':
            if len(s.ext)>0:
              for extension in s.ext:
                if s.os.path.splitext(item)[1].lower() == extension.lower():
                  files.append(item)
            else: files.append(item)
        else: folders.append(item)
      templist = folders
      for i in range(len(templist)):
        item = s.ru(templist[i])
        if item.lower() == prevdir:
          posindex = i+1
        icon = s.appuifw.Icon(s.iconpath,16388,16389)
        resultlist.append((item,icon))
        s.curnumlist.append(s.__s2d(item))
      templist = files
      for item in templist:
        icon = s.appuifw.Icon(s.iconpath,16390,16391)
        tit = s.ru(item)
        resultlist.append((tit,icon))
        s.curnumlist.append(s.__s2d(tit))

    s.body.set_list(resultlist,posindex)
    s.curlist = resultlist
    s.fulllist = resultlist
    s.appuifw.app.menu = [s.menuChoose]

  def browse_back(s):
    if s.curdir == u'root': return
    elif len(s.curdir) == 3:
      #s.appuifw.note(s.curdir[:-1])
      s.root(s.curdir[:-1])
    else:
      ind = s.curdir[:-1].rfind('\\')
      prevdir = s.curdir[ind+1:-1].lower()
      #s.appuifw.note(prevdir)
      s.curdir = s.os.path.dirname(s.curdir[:-1])
      if s.curdir[-1] != '\\': s.curdir += '\\'
      s.listdir(prevdir)

  def browse_forward(s):
    i = s.body.current()
    if s.curdir == u'root':
      path = s.e32.drive_list()[i]  + '\\'
    elif i == 0:
      s.browse_back()
      return
    else:
      path = s.curdir + s.curlist[i][0] + '\\'

    if s.os.path.isdir(s.ur(path)):
      s.curdir = path
      s.listdir()
    else:
      s.choose_item()

  def ch_made(s, p):
    s.curdir = p
    s.choice_made = True
    s.lock.signal()

  def choose_item(s):
    i = s.body.current()
    #s.appuifw.note(s.curnumlist[i-1])
    #return
    if s.curdir == u'root':
      if s.find == 'dir':
        s.ch_made(s.e32.drive_list()[i] + '\\')
    elif i == 0:
      s.browse_back()
    else:
      item = s.curdir + s.curlist[i][0]

      if s.os.path.isdir(s.ur(item)):
        if s.find == 'dir':
          s.ch_made(item)
      else:
        s.ch_made(item)

  def exit(s):
    s.choice_made = False
    s.lock.signal()

app_lock=Ao_lock()
__appname__=u'NetAlarm'
nomeeseguibileserver = 'netalarm_server_0xeaea0000.exe'
settingsfile=u'c:\\data\\others\\%s.cfg'% __appname__
numerotacche=1
numerointervallo=30
autostart=1
inferiore=0
testo=Text()
fid=0
for i in syspath:
	if i.find('resource')!=-1:
		cartellamif='%s\\apps\\' % syspath[fid]
	fid+=1
del fid
splashfile=u'%sNetAlarm GUI_0x%s_svg.mif' % (cartellamif,app.uid()) #Imposto il file di lavoro
#cartella='e:\\python\\'
#splashfile=u'%sNetAlarm GUI.mif' % (cartella)

def impostazioni():
	global numerotacche,numerointervallo,autostart
	oldtitolo=app.title
	app.title=u'Impostazioni'
	if ospath.exists(settingsfile):
		readsettings=openfile(settingsfile,'rb').readlines()[0]
		try: oldnumerotacche,oldnumerointervallo,oldautostart=unpack('>hhh',readsettings)
		except: oldnumerotacche,oldnumerointervallo,oldautostart=(numerotacche,numerointervallo,autostart)
	else: oldnumerotacche,oldnumerointervallo,oldautostart=(numerotacche,numerointervallo,autostart)
	data=[
	(
		u'Numero di tacche limite',
		'combo',
		(
		[u'Disattiva',u'1',u'2',u'3'],oldnumerotacche
		)
	),
	(
		u'Intervallo di tempo',
		'number',
		oldnumerointervallo
	),
	(
		u'Autostart',
		'combo',
		(
		[u'Off',u'On'],oldautostart
		)
	)
	]

	flags=FFormDoubleSpaced+FFormEditModeOnly
	f=Form(data,flags)
	f.execute()
	numerotacche=f[0][2][1] #0=0,1=1 ...
	numerointervallo=f[1][2]
	autostart=f[2][2][1] #0=0,1=1 ...
	
	#Salva e Carica Impostazioni
	settings=pack('>hhh',numerotacche,numerointervallo,autostart)
	f=openfile(settingsfile,'wb')
	f.write(settings)
	f.close()
	if (numerotacche==oldnumerotacche) and (numerointervallo==oldnumerointervallo) and (autostart==oldautostart):
		pass
	else:
	#riavviare=query2(u'Riavviare il server per applicare i cambiamenti?','query',ok=u'Si',cancel=u'No')
	#if riavviare: 
		#Riavvio il server
		dmn_stop(silent=1)
		dmn_start(silent=1)

	app.title=oldtitolo
	app.activate_tab(0)

def handle_tab(index):
    global lb
    if index == 0: myhome() # switch to application 1
    elif index == 1: impostazioni() # switch to application 2

def exit_key_handler():
	esci=query2(u'Uscire da %s?'% __appname__,'query',ok=u'Si',cancel=u'No')
	if esci: 
		app_lock.signal()
		app.set_exit()

def carica_settings():
	global numerotacche,numerointervallo,autostart
	if ospath.exists(settingsfile):
		readsettings=openfile(settingsfile,'rb').readlines()[0]
		try: numerotacche,numerointervallo,autostart=unpack('>hhh',readsettings)
		except: pass

def dmn_restart(silent=0):
	dmn_stop(silent=silent)
	dmn_start(silent=silent)

def dmn_start(silent=0):
	drives=drive_list()
	percorso=u'\\sys\\bin\\%s'%(nomeeseguibileserver)
	kill_app(u'NetAlarm Server*')
	eseguito=0
	for d in drives:
		try:
			start_exe(u'%s%s'%(d,percorso),'')
			eseguito=1
		except: continue
	if eseguito:
		ao_sleep(0.5)
		if not silent: note(u'Server avviato!','info')
		mymenu.pop(0)
		mymenu.insert(0,restart)
		mymenu.insert(0,stop)
		#mymenu=[stop,restart]
		#app.menu=mymenu
	else: 
		note(u'Impossibile trovare il server!\nProva a reinstallare il programma.','error')

def dmn_stop(silent=0):
	kill_app(u'NetAlarm Server*')
	if not silent: note(u'Server arrestato!','info')
	mymenu.pop(0)
	mymenu.pop(0)
	mymenu.insert(0,start)
	#mymenu=[start]
	#app.menu=mymenu
	
def handle_redraw(rect): 
	global img,photo
	if photo.size[0] == canvas.size[0]:
		canvas.blit(img)#pass
	else:
		del img
		del photo
		img=Image.new(app.layout(EScreen)[0])
		photo=Image.from_icon(splashfile,16384,(canvas.size[0],canvas.size[1]))
		img.blit(photo)
		canvas.blit(img)	

def myhome():
	img.blit(photo)
	app.body=canvas
	canvas.blit(img)

def file():
	app.set_tabs([],handle_tab)
	fileman = manager()
	path=fileman.AskUser('',ext = [".mp3",".wav",".aac"], title = 'Scegli file ...', wait = 'Attendere...', mselect = 'Seleziona', mopen = 'Apri', mback = 'Indietro')
	note(unicode(path),'info')
	app.set_tabs([u"Home", u"Impost."],handle_tab)
	
#kill_app(u'NetAlarm Server*')
start=(u'Avvia Server',dmn_start)
restart=(u'Riavvia Server',lambda:dmn_restart(silent=1))
stop=(u'Ferma Server',dmn_stop)
#settngs=(u'Impostazioni',impostazioni)
mymenu=[stop,restart,(u'Debug',((u'Scegli file',file),))]
app.title=__appname__
#try: app.orientation='portrait'
#except: pass
app.menu=mymenu
app.exit_key_handler=exit_key_handler
carica_settings()
#testo.set(u'Benvenuto in %s.'%app.title)
#testo.read_only = True
canvas=Canvas(event_callback=None,redraw_callback=handle_redraw)
img=Image.new(app.layout(EScreen)[0])
photo=Image.from_icon(splashfile,16384,(canvas.size[0],canvas.size[1]))
app.set_tabs([u"Home", u"Impost."],handle_tab)
myhome()
app_lock.wait()